#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.recommandInfoController import RecommandInfoController
from models.recommandInfoModel import RecommandInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings


class RecommandInfoService(RecommandInfoController):
    @classmethod
    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            if kwargs.get('ReUrl'):
                filter_list.append(cls.ReUrl == kwargs.get('ReUrl'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
          
            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            recommandInfo_info = db.session.query(RecommandInfo.AutoID, RecommandInfo.ReUrl, RecommandInfo.IsDelete, RecommandInfo.CreateTime).filter(*filter_list)
            
            count = recommandInfo_info.count()
            pages = math.ceil(count / size)
            recommandInfo_info = recommandInfo_info.limit(size).offset((page - 1) * size).all()
            
            if not recommandInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}
    
            # 处理返回的数据
            results = commons.query_to_dict(recommandInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
        
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
